import 'dart:io';

import 'package:permission_handler/permission_handler.dart';

import 'device_channel.dart';
import 'my_log.dart';

///权限检测工具类
class PermissionUtil {
  static String tag = "PermissionUtil";
  static bool debug = false;

  // static final PermissionUtil _instance = PermissionUtil._();

  PermissionUtil._();

  // factory PermissionUtil() => _instance;

  ///蓝牙是否已授权
  static Future<bool> isBluetoothGranted() async {
    return await Permission.bluetoothConnect.isGranted &&
        await Permission.bluetoothScan.isGranted &&
        await Permission.bluetooth.isGranted;
  }

  ///拥有位置权限和蓝牙权限返回 true
  static Future<bool> checkLocationAndBluetoothPermissions() async {
    debugLog("checkPermission");
    try {
      bool locationOk = (await Permission.locationWhenInUse.isGranted ||
              await Permission.locationAlways.isGranted ||
              await Permission.location.isGranted) &&
          await DeviceInfoChannel.isLocEnable();
      bool bleOk = false;
      if (Platform.isIOS) {
        bleOk = await Permission.bluetooth.isGranted &&
            await DeviceInfoChannel.isBluetoothEnable();
      } else if (Platform.isAndroid) {
        bleOk = (await Permission.bluetooth.isGranted &&
                    await Permission.bluetoothAdvertise.isGranted ||
                await Permission.bluetoothConnect.isGranted ||
                await Permission.bluetoothScan.isGranted) &&
            await DeviceInfoChannel.isBluetoothEnable();
      }

      debugLog("${await DeviceInfoChannel.isBluetoothEnable()}");
      debugLog("location:$locationOk ble:$bleOk");
      return locationOk && bleOk;
    } catch (e) {
      MyLog.e(tag, e.toString());
      return false;
    }
  }

  static Future<bool> requestStoragePermission() async {
    if (!await Permission.storage.isGranted) {
      await Permission.storage.request();
    }
    return Permission.storage.isGranted;
  }

  static Future<bool> requestBleAndLocationPermission() async {
    await [
      Permission.bluetooth,
      Permission.bluetoothConnect,
      Permission.bluetoothScan,
      Permission.bluetoothAdvertise,
      Permission.location,
      Permission.locationWhenInUse,

    ].request();
    return checkLocationAndBluetoothPermissions();
  }

  static void debugLog(String msg) {
    if (debug) MyLog.i(tag, msg);
  }
}
